﻿//给QMS排故单提交军检或排故结果提交军检的数据
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Longb
//create Date:2023-04-17
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFC.Common;
using UFC.DBUtility;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml;

namespace MESQualityHistoryRecord
{
    class SendDealFaultBillToQms
    {
        private const string DealFaultBill_XmlFileds = @"mfgOrderName,engineNo,dealFaultBillName,engineFamily,dealFaultType,productName,containerName,num,returnFactoryName,machineWorkHours,createEmployeeName,createDate,dealEmployeeFullName,dealDate,faultDesc,productDescription,affiliatedFactory,checkCustomer";
        private const string FaultBillDetail_XmlFileds = @"dealFaultSequence,dealFaultDesc,memo,factoryPassQty,factoryFailQty,factoryEmployeeName,factoryCheckerName,factoryWriterName,techniqueEmployeeName,auditEmployeeName,zjyszr";

        private static NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();

        public void Excute() 
        {
            try
            {
                DealFaultBillExcute();
            }catch(Exception ex){}
            try
            {
                DealFaultBillResultExcute();
            }catch(Exception ex){}
        }

        /// <summary>
        /// 排故单提交军检
        /// </summary>
        public void DealFaultBillExcute()
        {
            DataTable DealFaultBill_DT = GetDealFaultBillData("QMS_DealFaultBill");
            foreach (DataRow row in DealFaultBill_DT.Rows) 
            {
                var resQxml = CreateXMLForDealFaultBill(DealFaultBill_XmlFileds, row, "QMS_Send_DealFaultBill_Service", "m");
                LogHelp.WriteLog("排故单提交军检-推送XMl:" + resQxml);
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("排故单提交军检-返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["DEALFAULTBILLID"].ToString ()},{"RecordType","QMS_DealFaultBill"},
                        {"ContainerID",""},{"ContainerName",""},
                        {"ProductName",row["PRODUCTNAME"].ToString()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                    LogHelp.WriteLog(message);
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            } 
        }
        /// <summary>
        /// 排故单处理结果提交军检
        /// </summary>
        public void DealFaultBillResultExcute() 
        {
            DataTable DealFaultBill_DT = GetDealFaultBillData("QMS_DealFaultBillResolve");
            foreach (DataRow row in DealFaultBill_DT.Rows)
            {
                var resQxml = CreateXMLForDealFaultBill(DealFaultBill_XmlFileds + ",faultBillContainerName", row, "QMS_Send_DealFaultBillResolve_Service", "d");
                LogHelp.WriteLog("排故单处理结果提交军检-推送XMl:" + resQxml);
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("排故单处理结果提交军检-返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["DEALFAULTBILLID"].ToString ()},{"RecordType","QMS_DealFaultBillResolve"},
                        {"ContainerID",""},{"ContainerName",""},
                        {"ProductName",row["PRODUCTNAME"].ToString()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                    LogHelp.WriteLog(message);
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            } 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        private string CreateXMLForDealFaultBill(string strList, DataRow row, string qmsFunName,string type)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_QMS";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "MES_Send_Service";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);

            XmlNode root = doc.CreateElement("root");
            XmlNode qmsFun = doc.CreateElement("qmsFunName");
            qmsFun.InnerText = qmsFunName;
            root.AppendChild(qmsFun);

            XmlNode documentNode = doc.CreateElement("document");
            ReqNode.AppendChild(documentNode);

            XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
            foreach (string _key in strList.Split(','))
            {
                XmlNode mainData = doc.CreateElement(_key);
                mainData.InnerText =row.Table.Columns.Contains(_key)? row[_key].ToString():null;
                qmsDocument.AppendChild(mainData);
            }
            #region faultBillDetails 排故单处理结果
            if (type.Equals("d"))
            {
                XmlNode fbsNode = doc.CreateElement("faultBillDetails");//
                DataTable DealFaultBillResult = GetDealFaultBillResultData(row["DEALFAULTBILLID"].ToString());
                foreach (DataRow drow in DealFaultBillResult.Rows)
                {
                    if (!string.IsNullOrWhiteSpace(drow["DEALFAULTDESC"].ToString()))//排故方法为空，不传
                    {
                        XmlNode ItemNode = doc.CreateElement("faultBillDetail");//
                        foreach (string ht in FaultBillDetail_XmlFileds.Split(','))
                        {
                            XmlNode dData = doc.CreateElement(ht);
                            dData.InnerText = drow.Table.Columns.Contains(ht) ? drow[ht].ToString() : null;
                            ItemNode.AppendChild(dData);
                        }
                        fbsNode.AppendChild(ItemNode);
                    }
                }
                qmsDocument.AppendChild(fbsNode);
            }
            #endregion

            root.AppendChild(qmsDocument);
            documentNode.AppendChild(doc.CreateCDataSection("<root>" + root.InnerXml + "</root>"));
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
        /// <summary>
        /// 排故单提交军检数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetDealFaultBillData(string recordtype)
        {
            try
            {
                var strSql = @"SELECT d.DEALFAULTBILLID,m.MFGORDERNAME,d.ENGINENO,d.DEALFAULTBILLNAME,d.ENGINEFAMILY,d.DEALFAULTTYPE,
                            d.PRODUCTANDBATCH PRODUCTNAME,d.PRODUCTBATCHNO ContainerName ,nvl(d2.FROMQTY,0) num,f.FACTORYNAME ReturnFactoryName,
                            d.MACHINEWORKHOURS,e.EMPLOYEENAME CreateEmployeeName,to_char(d.CREATEDATE,'yyyy-MM-dd hh24:mi:ss') CREATEDATE,d.productname productDescription,
                            e2.EMPLOYEENAME DealEmployeeFullName,to_char(d2.CONFIRMTIME,'yyyy-MM-dd hh24:mi:ss') DealDate,d.FAULTDESC,u.ATTRIBUTEVALUE affiliatedFactory --u.ATTRIBUTEVALUE
                            FROM DEALFAULTBILL d 
                            LEFT JOIN MFGORDER m ON m.MFGORDERID =d.MFGORDERID 
                            LEFT JOIN FACTORY f ON f.FACTORYID =d.RETURNFACTORYID 
                            LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =d.CREATEEMPLOYEEID 
                            LEFT JOIN DEALFAULTBILLTRANSFER d2 ON d2.DEALFAULTBILLID =d.DEALFAULTBILLID 
                            LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =d2.CONFIRMEMPID
                            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.FACTORYID AND u.USERATTRIBUTENAME ='分厂代码'
                            left join WritetoOtherSystem ws on ws.parentid=d.DEALFAULTBILLID and ws.recordtype='{0}'
                            WHERE nvl(d.ISARMY,0)=1 and e2.EMPLOYEENAME is not null and ws.parentid is null and rownum<500  
                            ";
                if (recordtype.Equals("QMS_DealFaultBillResolve")) { strSql += " and AuditDate is not null"; }//结果提交：客户代表必须有
                DataSet myDS = OracleHelper.Query(string.Format(strSql, recordtype));
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 排故单处理结果提交军检数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetDealFaultBillResultData(string DealFaultBillID)
        {
            try
            {
                var strSql = @"SELECT DEALFAULTDESC,DEALFAULTSEQUENCE,MEMO 
                    ,'1'factoryPassQty,'0'factoryFailQty,'69400364'factoryEmployeeName,'69400364'factoryCheckerName,'69400364' factoryWriterName, '69400364' techniqueEmployeeName,
                    '69400364' auditEmployeeName,'69400364' ZJYSZR
                    FROM DealFaultStep WHERE DEALFAULTBILLID='" + DealFaultBillID + "'";
                DataSet myDS = OracleHelper.Query(strSql);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }


    }
}
